<template>
  <div class="login-container flx-center">
    <div class="login-box">
      <div class="login-left">
        <div class="title">伏特加-短期电力负荷 AI 预测实训</div>
        <div class="sub">轻松收集，高效预测</div>
        <img src="../../assets/login.png" alt="" />
      </div>

      <div class="login-form">
        <div class="login-logo">
          <img class="login-icon" src="../../assets/logo.png" alt="" />
          <p class="logo-text">{{ isLoginMode ? '欢迎登录' : '用户注册' }}</p>
        </div>

        <!-- 切换登录/注册标签 -->
        <div class="login-tabs flx-row">
          <div 
            :class="{ active: isLoginMode }" 
            @click="isLoginMode = true"
          >登录</div>
          <div 
            :class="{ active: !isLoginMode }" 
            @click="isLoginMode = false"
          >注册</div>
        </div>

        <!-- 登录表单 (JSON交互) -->
        <div v-if="isLoginMode" class="json-form">
          <div class="input-item">
            <el-input
              :prefix-icon="User"
              v-model="loginData.username"
              placeholder="用户名"
            ></el-input>
          </div>
          <div class="input-item">
            <el-input
              :prefix-icon="Lock"
              type="password"
              show-password
              v-model="loginData.password"
              placeholder="密码"
            ></el-input>
          </div>
          <div class="flx-row">
            <el-checkbox
              style="flex: 1"
              v-model="remember"
              label="记住密码"
              size="large"
            />
          </div>
          <div class="login-btn">
            <el-button
              :icon="CircleClose"
              round
              @click="resetLogin"
              size="large"
              >重置</el-button
            >
            <el-button
              :icon="UserFilled"
              round
              @click="submitLogin"
              size="large"
              type="primary"
              :loading="loading"
            >
              登录
            </el-button>
          </div>
        </div>

        <!-- 注册表单 (JSON交互) -->
        <div v-else class="json-form">
          <div class="input-item">
            <el-input
              :prefix-icon="User"
              v-model="registerData.username"
              placeholder="用户名"
            ></el-input>
          </div>
          <div class="input-item">
            <el-input
              :prefix-icon="Iphone"
              v-model="registerData.email"
              placeholder="邮箱"
            ></el-input>
          </div>
          <div class="input-item">
            <el-input
              :prefix-icon="Lock"
              type="password"
              show-password
              v-model="registerData.password"
              placeholder="密码"
            ></el-input>
          </div>
          <div class="login-btn">
            <el-button
              :icon="CircleClose"
              round
              @click="resetRegister"
              size="large"
            >重置</el-button>
            <el-button
              :icon="UserFilled"
              round
              @click="submitRegister"
              size="large"
              type="primary"
              :loading="loading"
            >
              注册
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="login">
import axios from "axios";
import { useRouter } from "vue-router";
import {
  CircleClose,
  UserFilled,
  Lock,
  User,
  Iphone,
} from "@element-plus/icons-vue";
import { Base64 } from "js-base64";
import { reactive, ref } from "vue";
import { ElMessage } from "element-plus";

// 状态管理
const loading = ref(false);
const isLoginMode = ref(true); // 切换登录/注册模式
const remember = ref(true); // 记住密码
const router = useRouter();

// 登录JSON数据
const loginData = reactive({
  username: "suming",
  password: "123456"
});

// 注册JSON数据
const registerData = reactive({
  username: "",
  email: "",
  password: ""
});

// 基础配置 - 后端接口地址
const API_BASE_URL = "http://localhost:5000";

// 登录请求 (JSON格式)
const submitLogin = async () => {
  // 简单校验
  if (!loginData.username || !loginData.password) {
    ElMessage.error("用户名和密码不能为空");
    return;
  }

  loading.value = true;
  try {
    // 发送JSON格式请求
    const response = await axios({
      url: `${API_BASE_URL}/login`,
      method: "POST",
      headers: {
        "Content-Type": "application/json" // 明确指定JSON格式
      },
      data: loginData // 直接传递JSON对象
    });

    const res = response.data;
    // 打印后端返回数据，确认token和redirect是否存在（调试用）
    console.log("后端登录响应：", res);

    if (res.success) {
      ElMessage.success(res.message);
      
      // 关键：存储后端返回的token到sessionStorage
      sessionStorage.setItem("token", res.token); 
      // 验证token是否存储成功（调试用）
      console.log("存储的token：", sessionStorage.getItem("token"));

      // 处理记住密码（原有逻辑不变）
      if (remember.value) {
        let encodedPwd = Base64.encode(loginData.password);
        localStorage.setItem("userInfo", JSON.stringify({
          username: loginData.username,
          password: encodedPwd
        }));
      } else {
        localStorage.removeItem("userInfo");
      }

      // 跳转首页（使用后端返回的redirect）
      router.push(res.redirect).catch(err => {
        // 捕获跳转失败错误（调试用）
        console.error("跳转失败：", err);
      });
    } else {
      ElMessage.error(res.message);
    }
  } catch (error) {
    ElMessage.error("登录失败，请检查网络或后端服务");
    console.error("登录错误:", error);
  } finally {
    loading.value = false;
  }
};

// 注册请求 (JSON格式)
const submitRegister = async () => {
  // 简单校验
  if (!registerData.username || !registerData.email || !registerData.password) {
    ElMessage.error("请完善注册信息");
    return;
  }

  loading.value = true;
  try {
    // 发送JSON格式请求
    const response = await axios({
      url: `${API_BASE_URL}/register`,
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      data: registerData // 直接传递JSON对象
    });

    const res = response.data;
    if (res.success) {
      ElMessage.success(res.message);
      isLoginMode.value = true; // 切换到登录页
    } else {
      ElMessage.error(res.message);
    }
  } catch (error) {
    ElMessage.error("注册失败，请检查网络或后端服务");
    console.error("注册错误:", error);
  } finally {
    loading.value = false;
  }
};

// 重置登录表单
const resetLogin = () => {
  loginData.username = "";
  loginData.password = "";
};

// 重置注册表单
const resetRegister = () => {
  registerData.username = "";
  registerData.email = "";
  registerData.password = "";
};

// 页面加载时读取记住的密码
const init = () => {
  const savedInfo = localStorage.getItem("userInfo");
  if (savedInfo) {
    const { username, password } = JSON.parse(savedInfo);
    loginData.username = username;
    loginData.password = Base64.decode(password);
    remember.value = true;
  }
};

// 初始化
init();
</script>

<style scoped lang="scss">
@import "./index.scss";

/* 新增样式 */
.json-form {
  .input-item {
    margin-bottom: 20px;
    width: 100%;
  }
}

.login-tabs {
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
  div {
    padding: 10px 20px;
    cursor: pointer;
    &.active {
      color: #409eff;
      border-bottom: 2px solid #409eff;
      font-weight: bold;
    }
  }
}
</style>